import 'package:flutter/material.dart';
import 'package:jetour_line/base_widget/base_scaffold.dart';
import 'package:jetour_line/base_widget/loading_widget.dart';
import 'package:jetour_line/base_widget/my_refresh_view.dart';
import "package:jetour_line/network/jetour_http.dart";
import 'package:jetour_line/pages/common/common_list_head_widget.dart';
import 'package:jetour_line/utils/aha_utils.dart';
import 'package:jetour_line/utils/extension_int.dart';
import '../../base_widget/base_image.dart';
import '../../model/city_list_model.dart';
import '../../models/guide_list_model.dart';
import '../../my_colors.dart';
import '../../utils/page_push_utils.dart';
import '../baseWidget/common_item_widget.dart';
import '../home/city_choose_page.dart';
import 'package:flutter/services.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
class CommonListPage extends StatefulWidget {
  final int type;

  int? cityId;

  String? cityName;

  CommonListPage({Key? key, required this.type, this.cityName, this.cityId})
      : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _CommonGuideListPage();
  }
}

class _CommonGuideListPage extends State<CommonListPage> {
  final MyRefreshViewController _controller = MyRefreshViewController();
  List<ListElement>? commonList;

  int page = 1;
  String city = '';
  int cityid = 0;
  int cate = 0;
  String? keyWord;
  final ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    super.initState();
    if (widget.cityId! > 0) {
      cityid = widget.cityId!;
      city = widget.cityName!;
    }


    getUserGuideList();
  }


  static const key = 'customCacheKey';
  static CacheManager instance = CacheManager(
    Config(
      key,
      stalePeriod: const Duration(days: 7),
      maxNrOfCacheObjects: 20,
      repo: JsonCacheInfoRepository(databaseName: key),
      fileService: HttpFileService(),
    ),
  );

  @override
  Widget build(BuildContext context) {
    return BaseScaffold(
      title: widget.type == 1 ? '精选共创路书' : '最新路书',
      body: GestureDetector(
        onTap: () => FocusManager.instance.primaryFocus?.unfocus(),
        child: Column(
          children: [
            Container(
              padding: EdgeInsets.only(left: 32.px, right: 32.px),
              width: double.infinity,
              height: 100.px,
              color: MyColors.white,
              alignment: Alignment.center,
              child: ClipRRect(
                borderRadius: BorderRadius.all(Radius.circular(32.px)),
                child: Container(
                  color: MyColors.colorF1F1F1,
                  height: 64.px,
                  child: Row(
                    children: [
                      Container(
                        color: Colors.transparent,
                        child: Row(
                          children: [
                            GestureDetector(
                              onTap: () {
                                PagePushUtils.push(context, ChooseCityScreen())
                                    .then((value) {
                                  CityModel model = value as CityModel;
                                  setState(() {
                                    city = model.name;
                                    cityid = model.id;
                                  });
                                  _controller.beginRef();
                                });
                              },
                              child: Container(
                                color: Colors.transparent,
                                child: Row(
                                  children: [
                                    SizedBox(
                                      height: 64.px,
                                      width: 26.px,
                                    ),
                                    Text(
                                      city,
                                      style: TextStyle(
                                          fontSize: 28.px,
                                          color: MyColors.color333333),
                                    ),
                                    SizedBox(
                                      width: 8.px,
                                    ),
                                    BaseImage(
                                      image: 'icon_meopen',
                                      width: 28.px,
                                      height: 28.px,
                                    ),
                                  ],
                                ),
                              ),
                            ),
                            Container(
                              margin:
                                  EdgeInsets.only(left: 15.px, right: 15.px),
                              width: 1.px,
                              height: 28.px,
                              color: MyColors.color999999,
                            ),
                            BaseImage(
                              image: 'ls_navbtn_search',
                              width: 40.px,
                              height: 40.px,
                            ),
                          ],
                        ),
                      ),
                      Expanded(
                          child: TextField(
                        onSubmitted: (value) {
                          keyWord = value;
                          _controller.beginRef();
                        },
                        onChanged: (value) {
                          keyWord = value;
                        },
                        style: TextStyle(
                            fontSize: 28.px, color: MyColors.color333333),
                        decoration: const InputDecoration(
                          border: InputBorder.none,
                          hintText: '请输入关键词',
                          isDense: true,
                          contentPadding: EdgeInsets.fromLTRB(8, 0, 0, 0),
                        ),
                      )),
                      SizedBox(
                        width: 26.px,
                      ),
                    ],
                  ),
                ),
              ),
            ),
            CommonListHeadWidget(
              title: "全部",
              callBack: (id) {
                cate = id;
                page = 1;
                getUserGuideList();
              },
            ),
            Expanded(
                child: Padding(
              padding: EdgeInsets.only(top: 20.px, left: 20.px, right: 20.px),
              child: MyRefreshView(
                refreshCallBack: (bool isUp) {
                  if (isUp) {
                    page == 1;
                  } else {
                    page++;
                  }
                  getUserGuideList();
                },
                controller: _controller,
                child: (commonList == null || commonList!.isEmpty)
                    ? Container(
                        width: double.infinity,
                        height: 1000.px,
                        child: LoadingWidget(
                            errorMsg: '快来分享您的路书吧',
                            type: (commonList != null && commonList!.isEmpty)
                                ? 1
                                : 0))
                    :
                       ListView.builder(
                          controller: _scrollController,
                          itemBuilder: (context, index) {
                            return CommonItemWidget(
                              comment: commonList![index],
                            );
                          },
                          itemCount: commonList!.length,
                        ),

              ),
            ))
          ],
        ),
      ),
    );
  }

  void getUserGuideList() async {
    Map<String, dynamic>? params = {};
    params['page'] = page;
    params['type'] = widget.type;
    params['city'] = cityid;
    params['cate'] = cate;
    if (keyWord != null) {
      params['keyword'] = keyWord;
    }

    print('resultresult ====$params');
    JetourHttp().get(JetourRouter.UserGuideList, params: params).then((result) {
      print('resultresult ====$result');
      FocusScope.of(context).unfocus();
      commonList ??= [];
      UserGuideListModel data = UserGuideListModel.fromJson(result);
      if (page == 1) {
        _scrollController.animateTo(0,
            duration: const Duration(milliseconds: 1), curve: Curves.ease);
        commonList!.clear();
      }
      setState(() {
        commonList!.addAll(data.list);
      });
      _controller.refreshEnd(page: page, maxPage: data.meta.maxPage);
    }).catchError((e) {
      _controller.refreshEnd();
    });
  }
}
